var CourseTable = {
    seItem: null,		//选中的条目
    me : "",
    href:"",//课程管理url
    countIndex: "",
    cache: "",
    param:{},//当前搜索条件
    isTrue:false ,//是否需要使用搜索条件
    currentPage:""
};


$(".nav-tabs li").on("click",function () {
    CourseTable.countIndex = $(this).index() || "";
    CourseTable.init(1);
});

/**
 * 初始化整个表格
 */
CourseTable.init = function(current){
    //页面加载
    // App.blockUI({
    //     message:"加载中",
    //     target: '#course-box',
    //     boxed: true,
    //     textOnly: true
    // });
    // return false;
    //如果是0传空
    var options = {
        courseStatus:CourseTable.countIndex,
        current:current,
        size:10
    };
    if(CourseTable.isTrue){
        options = $.extend({}, CourseTable.param, options);
        CourseTable.isTrue = false;
    }

    var ajax = new $ax(Feng.ctxPath+"/api/course/allParam", function(data){
        Feng.log("课程列表成功");
        if (data.total>0){
            //上下架过滤器
            template.helper('courseStatusFormat', function (inp) {
                if (inp === "1") {
                    return '<span class="label label-sm label-success">已上架</span>';
                }
                else{
                    return '<span class="label label-sm label-default">已下架</span>';
                }
            });
            //时间过滤器
            template.helper('dateFormat', function (inp) {
                if (inp !== "" && inp !== null) {
                    return inp.split(" ")[0];
                }
            });

            //课程季
            template.helper('courseSeasonFormat', function (inp) {
                switch (inp){
                    case "spring":
                        return "春季班";
                        break;
                    case "summer":
                        return "暑假班";
                        break;
                    case "autumn":
                        return "秋季班";
                        break;
                    case "winter":
                        return "寒假班";
                        break;
                }
            });
            //图片过滤器
            template.helper('pictureFormat', function (inp) {
               if(inp){
                   return Feng.ctxPath+"/file/getImage/"+inp;
               }
               else{
                   return Feng.ctxPath+"/img/logo_b.png";
               }
            });
            //价格
            template.helper('coursePriceFormat', function (inp) {
                if(inp!==""){
                    return numeral(inp).format('0,0.00');
                }
            });

            var outHtml = template("dataTmpl",data.records);
            $(".course-box").html(outHtml);

            CourseTable.initPagination(data);
            // App.unblockUI('#course-box');
            $(".loading-container").hide();
        }
        else{
            $(".loading-container").show();
            $(".course-box").html("");
            $("#dt-data-pagination").html("");
        }
    },function(data){
        Feng.error("课程列表失败!");
        // App.handleSidebarAjaxContent();
        $(".loading-container").show();
        $(".course-box").html("");
        $("#dt-data-pagination").html("");
    });
    ajax.data=options;
    ajax.start();
    CourseTable.currentPage = current;
    localStorage.removeItem("course_list_currentPage");
};

//分页
CourseTable.initPagination = function(data){
    $("#dt-data-pagination").pagination(data.total, {
        num_edge_entries: 1, //边缘页数
        num_display_entries: 4, //主体页数
        callback: CourseTable.paginationFunction,
        items_per_page: data.size, //每页显示1项
        current_page: data.current-1,
        prev_text: "上一页",
        next_text: "下一页",
        link_to: "javascript:void(0)",
        call_callback_at_once: false
    });
};

//分页点击事件
CourseTable.paginationFunction = function(currentPage) {
    CourseTable.init(currentPage + 1);
};

/**
 * 点击搜索按钮
 */
function clickSearch(){
    var options = {
        current: 1,
        size: 10,
        courseStatus:CourseTable.countIndex
    };
    //课程名称
    var val_search_name = $("#txt_search_name").val();
    if (val_search_name !== "" && val_search_name !== null) {
        options.courseName = val_search_name;
    }
    //课程类型
    var val_search_classType = $("#txt_search_classType").find("option:selected").val();
    if (val_search_classType !== "" && val_search_classType !== null && val_search_classType !== "-1") {
        options.courseClass = val_search_classType;
    }

    //课程年级
    var val_search_courseGrade = $("#txt_search_courseGrade").find("option:selected").val();
    if (val_search_courseGrade !== "" && val_search_courseGrade !== null && val_search_courseGrade !== "-1") {
        options.courseGrade = val_search_courseGrade;
    }

    var ajax = new $ax(Feng.ctxPath+"/api/course/allParam", function(data){
        Feng.log("课程列表成功");
        if (data.total>0){
            //上下架过滤器
            template.helper('courseStatusFormat', function (inp) {
                if (inp === "1") {
                    return '<span class="label label-sm label-success">已上架</span>';
                }
                else{
                    return '<span class="label label-sm label-default">已下架</span>';
                }
            });
            //时间过滤器
            template.helper('dateFormat', function (inp) {
                if (inp !== "" && inp !== null) {
                    return inp.split(" ")[0];
                }
            });

            //课程季
            template.helper('courseSeasonFormat', function (inp) {
                switch (inp){
                    case "spring":
                        return "春季班";
                        break;
                    case "summer":
                        return "暑假班";
                        break;
                    case "autumn":
                        return "秋季班";
                        break;
                    case "winter":
                        return "寒假班";
                        break;
                }
            });
            //图片过滤器
            template.helper('pictureFormat', function (inp) {
                if(inp){
                    return Feng.ctxPath+"/file/getImage/"+inp;
                }
                else{
                    return Feng.ctxPath+"/img/logo_b.png";
                }
            });
            //价格
            template.helper('coursePriceFormat', function (inp) {
                if(inp!==""){
                    return numeral(inp).format('0,0.00');
                }
            });

            var outHtml = template("dataTmpl",data.records);
            $(".course-box").html(outHtml);

            CourseTable.initPagination(data);
            $(".loading-container").hide();
        }
        else{
            $(".loading-container").show();
            $(".course-box").html("");
            $("#dt-data-pagination").html("");
        }
    },function(data){
        Feng.error("课程列表失败!");
        $(".loading-container").show();
        $(".course-box").html("");
        $("#dt-data-pagination").html("");
    });
    ajax.data=options;
    ajax.start();

    CourseTable.param = options;
}

/**
 * 点击添加按钮时，跳转到新增页面
 * @returns
 */
$("#btn_add").on("click",function () {
    window.location.href=Feng.ctxPath+"/course/info/page";
});

/**
 *  存储当前页
 * @param currentPage
 */
function storePage(currentPage){
    localStorage.setItem("course_list_currentPage",currentPage);
}


/**
 * 点击编辑按钮时，跳出用户详情对话框
 * @returns
 */
function editBtn(uid){
    var course_x =  window.scrollX;
    var course_y = window.scrollY;
    localStorage.setItem("course_list_x",course_x);
    localStorage.setItem("course_list_y",course_y);

    storePage(CourseTable.currentPage);
    window.location.href=Feng.ctxPath+"/course/info/page?id="+uid;
}


/**
 * 课程下架
 * @param uid 课程的id
 * @returns
 */
function deleteBtn(uid,deleteName){
    layer.confirm('是否下架课程:'+deleteName, {icon: 10, title:'是否下架课程?'}, function(index){
        var ajax = new $ax(Feng.ctxPath + "/course/soldOut", function (data) {
            if (data.success){
                Feng.success("下架成功!");
                layer.close(index);

                CourseTable.isTrue = true;
                CourseTable.init(1);
                window.scroll(0, 0);
            }else if(data.code === 2){
                Feng.error(data.msg);
            }else{
                Feng.error("下架失败!");
            }
        },function(data){
            Feng.error("下架失败!");
        });
        ajax.set("id",uid);
        ajax.start();
    });

}

/**
 * 初始化导入弹出框
 */
CourseTable.initCourseInputDialog = function () {
    //加载模板文件下载连接
    $("#excelDownload").attr("href", "http://" + window.location.host + "/child/course/excel/download/");
    $("#importMsg").hide();
    this.cache = $("#courseInputDialog").html();
    $("#courseInputDialog").html('');
};

/**
 * 点击导入按钮时，弹出导入框
 */
$("#btn_excel_import").on("click", function () {
    layer.open({
        type: 1,
        title: '导入课程',
        skin: 'layui-layer-lan', //加上边框
        area: ['470px', '300px'],//宽高
        content: CourseTable.cache,
        success: function (layero, index) {
            //层弹出成功后回调方法
            CourseTable.excelInput();
        },
        maxmin: true,
        scrollbar: false,
        btn: ['关闭'],
        btnAlign: 'r',  //默认值
        yes: function (index, layero) {
            layer.close(index); //如果设定了yes回调，需进行手工关闭
            $("#importMsg").hide();
            CourseTable.init(1)
        },
        cancel: function (index, layero) {
            //右上角关闭按钮触发的回调
            layer.close(index);
            $("#importMsg").hide();
        }
    });
});

/**
 * 查看报名会员详情
 * @returns
 */
function viewItems(dataId){
    var index = layer.open({
        type: 1,
        title: '报名会员详情列表',
        skin: 'layui-layer-lan', //加上边框
        area: [VipUserItemsTable.width, VipUserItemsTable.height],//宽高
        content: VipUserItemsTable.cache,
        success: function(layero, index){
            //初始化会员信息表格
            VipUserItemsTable.init(dataId);
        },
        maxmin: true,
        scrollbar: false,
        cancel:function (index, layero) {
            //右上角关闭按钮触发的回调
            layer.close(index);
        }
    });
    VipUserItemsTable.currentLayerIndex = index;
}

/**
 * excel导入教师
 */
CourseTable.excelInput = function () {
    $("#file_excel").uploadify({
        height: 30,
        swf: Feng.ctxPath + '/js/assets/lib/uploadify/uploadify.swf?ver=' + Math.random(),
        uploader: Feng.ctxPath + '/course/excel/input/?ver=' + Math.random(),
        width: 200,
        // wmode         : 'transparent',
        fileObjName: 'file',
        fileTypeExts: '*.xlsx;*.xls;', //文件后缀限制 默认：'*.
        // fileSizeLimit: '20480KB', //文件大小限制 0为无限制 默认KB
        queueSizeLimit: 1,
        multi: false,
        buttonText: '导入课程信息', //按钮文字
        removeCompleted: false, //上传成功后的文件，是否在队列中自动删除
        overrideEvents: ['onSelectError', 'onUploadSuccess', 'onUploadError'],//重写事件
        //选择关闭事件
        // onDialogClose:function () {},
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            Feng.error(msgText);
        },

        //检测FLASH失败调用
        'onFallback': function () {
            alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        ////文件上传成功后的回掉方法
        'onUploadSuccess': function (file, data, response) {
            data = JSON.parse(data);
            if (data.success) {
                $("#importMsg").text("导入课程信息成功").show();
            } else if (data.code === 2) {
                $("#importMsg").text(data.msg).show();
            } else {
                $("#importMsg").text("导入课程信息失败").show();
            }
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            $("#importMsg").hide();
            Feng.error("上传出现异常，请重新上传" + errorString);
        }

    });

};


$(function(){
    var currentPage = localStorage.getItem("course_list_currentPage");
    if (currentPage == null){
        currentPage = 1;
    }

    CourseTable.init(currentPage);
    CourseTable.initCourseInputDialog();
    VipUserItemsTable.initView();
    //缓存课程管理页面地址
    CourseTable.href = $("#iframe_tab_10211").attr("src");

    var course_list_x = localStorage.getItem("course_list_x");
    var course_list_y = localStorage.getItem("course_list_y");
    if (course_list_x != null && course_list_y != null){
        window.scrollTo(course_list_x,course_list_y);
        localStorage.setItem("course_list_x","0");
        localStorage.setItem("course_list_y","0");
    }

});
